from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import argparse
import backtrader as bt
import pandas as pd
from Utils.TushareUtil import TuShare
import backtrader.feeds as btfeeds
from DB.FuturesDB import getFutureMinPrice, getFutureDailyPrice
import pandas


# 获取数据的频率跟策略执行的一致
def build_backtest_dataset(start_date: str, end_date: str):
    """构造配套 backtesting 用的数据集"""
    # 使用Tushare API获取股票000001.SH的日线行情
    tushare_token = '4b17847b701af3b6cd85fd6b7fc43c3805c37f1ed8fd18353b46f140'
    my_ts = TuShare(tushare_token, max_retry=10)
    df = my_ts.daily(ts_code='000001.SZ', start_date=start_date, end_date=end_date)
    # 处理数据，确保数据格式符合Backtrader的要求
    df = df.sort_values(by='trade_date')  # 按日期排序
    df['trade_date'] = pd.to_datetime(df['trade_date'])  # 将日期列转换为datetime类型
    df.set_index('trade_date', inplace=True)  # 将日期列设置为索引
    df = df[['open', 'high', 'low', 'close', 'vol']]  # 选择需要的列
    df.columns = ['open', 'high', 'low', 'close', 'volume']  # 重命名列名
    return df


def runstrat():
    args = parse_args()

    # Create a cerebro entity
    cerebro = bt.Cerebro(stdstats=False)

    # Add a strategy
    cerebro.addstrategy(bt.Strategy)

    train_start = '20190107'
    train_end = '20241231'
    dataframe = build_backtest_dataset(train_start, train_end)

    if not args.noprint:
        print('--------------------------------------------------')
        print(dataframe)
        print('--------------------------------------------------')

    # Pass it to the backtrader datafeed and add it to the cerebro
    data = bt.feeds.PandasData(dataname=dataframe)
    cerebro.adddata(data)

    # Run over everything
    cerebro.run()

    # Plot the result
    # cerebro.plot(style='candlestick')


def parse_args():
    parser = argparse.ArgumentParser(
        description='Pandas test script')

    parser.add_argument('--noheaders', action='store_true', default=False,
                        required=False,
                        help='Do not use header rows')

    parser.add_argument('--noprint', action='store_true', default=False,
                        help='Print the dataframe')

    return parser.parse_args()


if __name__ == '__main__':
    runstrat()